package com.tomtaw.web.callnumber;

import static com.tomtaw.web.callnumber.BootBroadcastReceiver.BOOT_LAUNCH;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.Logger;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.flattener.PatternFlattener;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.FileSizeBackupStrategy;
import com.elvishew.xlog.printer.file.backup.FileSizeBackupStrategy2;
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy;
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;
import com.google.android.material.navigation.NavigationView;
import com.tomtaw.web.callnumber.storage.AppPrefs;
import com.tomtaw.web.callnumber.ui.home.HomeViewModel;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final String CUSTOM_SELECT = "CUSTOM_SELECT";
    private static final String CUSTOM_URL_ADDRESS = "CUSTOM_URL_ADDRESS";
    private static final String URL_ADDRESS = "URL_ADDRESS";
    private static final String CODE_ADDRESS = "CODE_ADDRESS";
    private static final String CHECK_CODE_ADDRESS = "CHECK_CODE_ADDRESS";
    private static final String CUSTOMER_ID = "CUSTOMER_ID";
    private static final String TIME_INTERVAL = "TIME_INTERVAL";
    public static final String DEBUG_MODEL = "DEBUG_MODEL";
    private AppBarConfiguration mAppBarConfiguration;
    private HomeViewModel mViewModel;
    private MediaPlayer mMediaPlayer;
    private String mUrlAddress;
    private int mTimeInterval = 12;
    private final Handler mHandler = new Handler();
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (mViewModel != null) {
                Log.d("mRunnable", "run: " + mUrlAddress);
                mViewModel.getText().postValue(mUrlAddress);
                mHandler.postDelayed(this, (long) mTimeInterval  *60* 60 * 1000);
            }
        }
    };

    MediaPlayer mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent("com.tomtaw.web.callnumber.BootBroadcastReceiver");
        ComponentName componentName = new ComponentName(this, "com.tomtaw.web.callnumber.BootBroadcastReceiver");
        intent.setComponent(componentName);
        sendBroadcast(intent);


        AndPermission.with(this).runtime()
                .permission(new String[]{Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_EXTERNAL_STORAGE,Permission.RECORD_AUDIO})
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        LogConfiguration config = new LogConfiguration.Builder()
                                .logLevel(AppPrefs.getSharedBoolean(DEBUG_MODEL, true) ? LogLevel.ALL : LogLevel.NONE)             // 指定日志级别，低于该级别的日志将不会被打印，默认为 LogLevel.ALL
                                .tag("MY_TAG")                                         // 指定 TAG，默认为 "X-LOG"
                                .build();
                        String log_file_path = getExternalFilesDir("").getAbsoluteFile().getPath();
                        Printer filePrinter = new FilePrinter                      // 打印日志到文件的打印器
                                .Builder(log_file_path)                             // 指定保存日志文件的路径
                                .fileNameGenerator(new DateFileNameGenerator())        // 指定日志文件名生成器，默认为
                                // ChangelessFileNameGenerator("log")
                                .backupStrategy(new FileSizeBackupStrategy2(100 * 1024 * 1024, 1))             //
                                // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
                                .cleanStrategy(new FileLastModifiedCleanStrategy(7*24 * 60 * 60 * 1000))     //
                                // 指定日志文件清除策略，默认为 NeverCleanStrategy()
                                .flattener(new PatternFlattener("{d} {l}/{t}: {m}"))
                                .build();

                        XLog.init(                                                 // 初始化 XLog
                                config,                                                // 指定日志配置，如果不指定，会默认使用 new
                                // LogConfiguration.Builder().build()
                                filePrinter);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {

                    }
                }).start();


        final DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupWithNavController(navigationView, navController);


        mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);


        findViewById(R.id.setting_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final EditText editText = new EditText(MainActivity.this);
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("请输入密码");
                dialog.setView(editText);
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if ("ew".equalsIgnoreCase(editText.getText().toString())) {
                            drawer.open();
                        } else {
                            Toast.makeText(MainActivity.this, "密码错误，请重新输入", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.show();


            }
        });

        final View headview = navigationView.inflateHeaderView(R.layout.nav_header_main);
        final LinearLayout standardLl = headview.findViewById(R.id.standard_ll);
        final EditText urlEdt = headview.findViewById(R.id.url_edt);
        final EditText codeEdt = headview.findViewById(R.id.code_edt);
        final EditText checkCodeEdt = headview.findViewById(R.id.check_code_edt);
        final EditText customerIdEdt = headview.findViewById(R.id.customer_id_edt);
        final EditText timeIntervalEdt = headview.findViewById(R.id.time_interval_edt);
        final EditText urlCustomEdt = headview.findViewById(R.id.url_custom_edt);
        final CheckBox customChk = headview.findViewById(R.id.custom_chk);
        customChk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    standardLl.setVisibility(View.GONE);
                    urlCustomEdt.setVisibility(View.VISIBLE);
                } else {
                    standardLl.setVisibility(View.VISIBLE);
                    urlCustomEdt.setVisibility(View.GONE);
                }
            }
        });
        TextView saveTv = headview.findViewById(R.id.save_tv);
        saveTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftInput(v);
                boolean isSel = customChk.isChecked();
                AppPrefs.putSharedBoolean(CUSTOM_SELECT, isSel);
                if (isSel) {
                    String url = urlCustomEdt.getText().toString();
                    if (StringUtil.isBlank(url)) {
                        Toast.makeText(MainActivity.this, "请输入自定义URL", Toast.LENGTH_LONG).show();
                    } else {
                        //http://192.168.1.173:9003?code=test01&pwd=123456&platform=android&sign=app

                        AppPrefs.putSharedString(CUSTOM_URL_ADDRESS, url);
                        Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();

                        mUrlAddress = url;
                        mViewModel.getText().postValue(mUrlAddress);
                        drawer.close();
                    }
                } else {
                    String url = urlEdt.getText().toString();
                    String code = codeEdt.getText().toString();
                    String checkCode = checkCodeEdt.getText().toString();
                    String customerId = customerIdEdt.getText().toString();
                    String timeInterval = timeIntervalEdt.getText().toString();
                    if (StringUtil.isBlank(url)) {
                        Toast.makeText(MainActivity.this, "请输入叫号屏地址", Toast.LENGTH_LONG).show();
                    } else if (StringUtil.isBlank(code)) {
                        Toast.makeText(MainActivity.this, "请输入叫号屏编码", Toast.LENGTH_LONG).show();
                    } else if (StringUtil.isBlank(checkCode)) {
                        Toast.makeText(MainActivity.this, "请输入叫号屏校验码", Toast.LENGTH_LONG).show();
                    } else if (StringUtil.isBlank(customerId)) {
                        Toast.makeText(MainActivity.this, "请输入客户ID", Toast.LENGTH_LONG).show();
                    } else {
                        //http://192.168.1.173:9003?code=test01&pwd=123456&platform=android&sign=app

                        AppPrefs.putSharedString(URL_ADDRESS, url);
                        AppPrefs.putSharedString(CODE_ADDRESS, code);
                        AppPrefs.putSharedString(CHECK_CODE_ADDRESS, checkCode);
                        AppPrefs.putSharedString(CUSTOMER_ID, customerId);


                        Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();

                        mUrlAddress = url + "?code=" + code + "&pwd=" + checkCode
                                + "&platform=android&sign=app&specify_tenancy_id=" + customerId;
                        mViewModel.getText().postValue(mUrlAddress);
                        drawer.close();
                    }

                    try {
                        int time = Integer.parseInt(timeInterval);

                        mTimeInterval = time > 0 ? time : 12;
                        AppPrefs.putSharedInt(TIME_INTERVAL, mTimeInterval);

                    } catch (NumberFormatException e) {
                        AppPrefs.putSharedInt(TIME_INTERVAL, 12);
                    }
                }

            }
        });

        final EditText audioUrlEdt = headview.findViewById(R.id.audio_url_edt);
        TextView remoteAudioTestTv = headview.findViewById(R.id.remote_audio_test_tv);
        remoteAudioTestTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (mPlayer != null ) {
                        if (mPlayer.isPlaying()){
                            mPlayer.stop();
                            mPlayer.reset();
                        }
                        mPlayer.release();
                        mPlayer = null;
                    }

                    mPlayer = new MediaPlayer();
                    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            XLog.i("开始播放音频");
                            mPlayer.start();
                        }
                    });

                    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            XLog.e("播放错误："+audioUrlEdt.getText().toString()+",错误码:"+what+","+extra);
                            return true;
                        }
                    });

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            XLog.e("player播放测试成功");
                        }
                    });

                    mPlayer.setDataSource(audioUrlEdt.getText().toString());
                    mPlayer.prepareAsync();


                } catch (Exception e) {
                    XLog.e(e.getMessage());
                }
            }
        });

        TextView localAudioTestTv = headview.findViewById(R.id.local_audio_test_tv);
        localAudioTestTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    if (mPlayer != null) {
                        mPlayer.stop();
                        mPlayer.reset();
                        mPlayer.release();
                        mPlayer = null;
                    }

                    mPlayer = MediaPlayer.create(MainActivity.this, R.raw.soundtest);
                    mPlayer.start();


                } catch (Exception e) {
                    XLog.e(e.getMessage());
                }
            }
        });

        Switch bootSW = headview.findViewById(R.id.boot_sw);
        bootSW.setChecked(AppPrefs.getSharedBoolean(BOOT_LAUNCH, true));
        bootSW.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AppPrefs.putSharedBoolean(BOOT_LAUNCH, isChecked);
            }
        });
        Switch debugSW = headview.findViewById(R.id.debug_sw);
        debugSW.setChecked(AppPrefs.getSharedBoolean(DEBUG_MODEL, true));
        debugSW.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AppPrefs.putSharedBoolean(DEBUG_MODEL, isChecked);
            }
        });
        headview.findViewById(R.id.exit_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });

        String url = AppPrefs.getSharedString(URL_ADDRESS, "http://www.eworlds.com.cn:9001/callclientweb/");
        urlEdt.setText(url == null ? "" : url);

        String code = AppPrefs.getSharedString(CODE_ADDRESS);
        codeEdt.setText(code == null ? "" : code);

        String checkCode = AppPrefs.getSharedString(CHECK_CODE_ADDRESS, "123456");
        checkCodeEdt.setText(checkCode == null ? "" : checkCode);

        String customerId = AppPrefs.getSharedString(CUSTOMER_ID, "1292780114131554304");
        customerIdEdt.setText(customerId == null ? "" : customerId);

        String customUrl = AppPrefs.getSharedString(CUSTOM_URL_ADDRESS, "http://192.168.200.13:9050/style07" +
                ".html?spot=102&code=102");
        urlCustomEdt.setText(customUrl == null ? "" : customUrl);

        boolean isCustomUrlSel = AppPrefs.getSharedBoolean(CUSTOM_SELECT, false);
        customChk.setChecked(isCustomUrlSel);

        if (isCustomUrlSel) {
            standardLl.setVisibility(View.GONE);
            urlCustomEdt.setVisibility(View.VISIBLE);
            if (StringUtil.isBlank(customUrl)) {
                drawer.open();
            } else {
                mUrlAddress = customUrl;
                mViewModel.getText().postValue(mUrlAddress);
            }
        } else {
            standardLl.setVisibility(View.VISIBLE);
            urlCustomEdt.setVisibility(View.GONE);
            if (StringUtil.isBlank(url) || StringUtil.isBlank(code)
                    || StringUtil.isBlank(checkCode)) {
                drawer.open();
            } else {
                mUrlAddress = url + "?code=" + code + "&pwd=" + checkCode
                        + "&platform=android&sign=app&specify_tenancy_id=" + customerId;
                mViewModel.getText().postValue(mUrlAddress);
            }
        }

        mTimeInterval = AppPrefs.getSharedInt(TIME_INTERVAL, 12);
        timeIntervalEdt.setText(String.format("%d", mTimeInterval));
        mHandler.postDelayed(mRunnable, (long) mTimeInterval  *60* 60 * 1000);


    }


    @Override
    public void onBackPressed() {
        System.exit(0);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    protected void hideSoftInput(View view) {
        if (isFinishing()) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(
//                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                            // | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                            | View.SYSTEM_UI_FLAG_FULLSCREEN
//                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
//        }
//    }
}